<?php

/**
 * 订单列表
 * @author renjianhong
 * @date 2021-8-03 16:47
 */
namespace Modules\Order\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Modules\Order\Http\Controllers\Controller;
use Modules\Order\Entities\Order;
use Modules\Order\Entities\OrderDetail;
use Modules\Order\Entities\User;
use App\Models\Express;


class OrderController extends Controller
{
    
    /**
     * 订单列表
     */
    public function list(Request $request, Order $OrderModel)
    { 
        $url = $_SERVER['SERVER_NAME'];
        
        $express_list = Express::get()->toArray();
        $order_id = $request->input('order_id');

        return view('order::admin.order.list',compact('OrderModel','express_list','order_id'));
    }

    /**
     * ajax获取列表数据
     */
    public function ajaxList(Request $request, Order $OrderModel)
    {
        $pagesize = $request->input('limit'); // 每页条数
        $page = $request->input('page',1);//当前页
        $order_no = $request->input('order_no');
        $nickname = $request->input('nickname');
        $name = $request->input('name');
        $mobile = $request->input('mobile');
        $begin_time = $request->input('begin_time');//开始时间
        $end_time = $request->input('end_time');//结束时间
        $order_status = $request->input('order_status');//订单状态
        $order_id = $request->input('order_id');
        
        $where = [
            ['order.order_no', 'like', '%'.$order_no.'%'],
            ['order.name', 'like', '%'.$name.'%'],
            ['users.nickname', 'like', '%'.$nickname.'%'],
            ['order.is_delete', '=', '0'],
        ];
        if($mobile){
            $where[] = ['order.mobile', '=', $mobile];
        }
        
        if($begin_time && $end_time){
            if($begin_time > $end_time){
                return $this->failed('开始时间不能大于截止时间');
            }
        }
        if($begin_time){
            $where[] = ['order.created_at', '>=', $begin_time];
        }
        if($end_time){
            $where[] = ['order.created_at', '<=', $end_time];
        }
        
        if($order_status != ''){
            if($order_status == 5){
                $where[] = ['order.is_recycle', '=', 1];
            }else{
                $where[] = ['order.order_status', '=', $order_status];
            }
        }
        if($order_id){
            $where[] = ['order.id', '=', $order_id];
        }
        //获取总条数
        $count = $OrderModel
                ->leftJoin('users', 'users.id', '=', 'order.user_id')
                ->where($where)
                ->count();
        
        //求偏移量
        $offset = ($page-1)*$pagesize;
        $list = $OrderModel
                ->leftJoin('users', 'users.id', '=', 'order.user_id')   
                ->where($where)
                ->select('order.*','users.nickname','users.avatar')
                ->orderByDesc('id')->offset($offset)->limit($pagesize)->get();
        foreach($list as $key => $v){
            $order_detail = OrderDetail::where('order_id',$v['id'])->get();//订单商品详情
            foreach($order_detail as $index => &$dl){
                $order_detail[$index]['goods_attr'] = json_decode($dl['goods_attr'],true);
                $is_domain = $OrderModel->getIsDomain($dl['goods_pic']);
                if($is_domain){
                    $order_detail[$index]['goods_pic'] = $dl['goods_pic'];
                }else{
                    $order_detail[$index]['goods_pic'] = $OrderModel->getShowImage($dl['goods_pic']);
                }
            }
            $list[$key]['order_detail'] = $order_detail;
            $is_domain = $OrderModel->getIsDomain($v['avatar']);
            if($is_domain){
                $list[$key]['avatar'] = $v['avatar'];
            }else{
                $list[$key]['avatar'] = $OrderModel->getShowImage($v['avatar']);
            }
            $list[$key]['order_status_name'] = $OrderModel->getOrderStatus($v['order_status']);
            
        }
        
        return $this->success(compact('list', 'count'));
    }

    /**
     * 取消订单
     */
    public function cancel(Request $request, Order $OrderModel)
    {
        if($request->isMethod('post')){
            $id = $request->input('id');
            if($id){
                $reulst = $OrderModel->where('id',$id)->update(['order_status'=>4]);
                if($reulst){
                    return $this->success('操作成功');
                }else{
                    return $this->failed('操作失败');
                }
            }else{
                return $this->failed('缺少参数id');
            }
        }
    }

    /**
     * 订单详情
     */
    public function detail(Request $request, Order $OrderModel)
    {   
        if($request->isMethod('post')){
            $order_id = $request->input('id');
            $seller_comments = $request->input('seller_comments');
            $result = $OrderModel->where('id',$order_id)->update(['seller_comments'=>$seller_comments]);
            if($result){
                return $this->success('操作成功');
            }else{
                return $this->failed('操作失败');
            }
        }else{
            $id = $request->input('id');
            $info = $OrderModel
                    ->leftJoin('users', 'users.id', '=', 'order.user_id')   
                    ->where('order.id',$id)
                    ->select('order.*','users.nickname','users.avatar')
                    ->first();
            $info->order_status_name = $OrderModel->getOrderStatus($info['order_status']);

            $order_detail = OrderDetail::where('order_id',$info['id'])->get();//订单商品详情
            foreach($order_detail as $index => &$dl){
                $order_detail[$index]['goods_attr'] = json_decode($dl['goods_attr'],true);
            }
            return view('order::admin.order.detail',compact('info','order_detail'));
        }
        
    }

    /**
     * 删除订单
     */
    public function delete(Request $request, Order $OrderModel){
        if($request->isMethod('post')){
            $id = $request->input('id');
            if($id){
                $reulst = $OrderModel->where('id',$id)->update(['is_delete'=>1]);
                if($reulst){
                    OrderDetail::where('order_id',$id)->update(['is_delete'=>1]);
                    return $this->success('操作成功');
                }else{
                    return $this->failed('操作失败');
                }
            }else{
                return $this->failed('缺少参数id');
            }
        }
    }

    /**
     * 批量删除-清空回收站
     */
    public function batchDelete(Request $request, Order $OrderModel){
        if($request->isMethod('post')){
            
            $order_list = $OrderModel->where([['is_delete','=',0],['is_recycle','=',1]])->get();
            $id = [];
            foreach($order_list as $key => $v){
                $id[] = $v['id'];
            }
            
            $reulst = $OrderModel->whereIn('id',$id)->update(['is_delete'=>1]);
            if($reulst){
                OrderDetail::whereIn('order_id',$id)->update(['is_delete'=>1]);
                return $this->success('操作成功');
            }else{
                return $this->failed('操作失败');
            }
        }
    }

     /**
     * 移入回收站
     * 移出回收站
     */
    public function recycle(Request $request, Order $OrderModel)
    {
        if($request->isMethod('post')){
            $id = $request->input('id');
            if($id){
                $order = $OrderModel->where('id',$id)->select('is_recycle')->first();
                if($order->is_recycle == 1){
                    $recycle = 0;
                }else{
                    $recycle = 1;
                }
                $reulst = $OrderModel->where('id',$id)->update(['is_recycle'=>$recycle]);
                if($reulst){
                    return $this->success('操作成功');
                }else{
                    return $this->failed('操作失败');
                }
            }else{
                return $this->failed('缺少参数id');
            }
        }
    }
    
    /**
     * 订单发货
     */
    public function send(Request $request, Order $OrderModel)
    {
        if($request->isMethod('post')){
            $id = $request->input('id');
            $express_id = $request->input('express');
            $express = Express::find($express_id);
            $data['express_no'] = $request->input('express_no');
            $data['express_code'] = $express->code;
            $data['express'] = $express->name;
            $data['seller_comments'] = $request->input('seller_comments');
            
            $reulst = $OrderModel->where('id',$id)->update($data);
            if($reulst){
                $OrderModel->where('id',$id)->update(['order_status'=>2]);
                return $this->success('操作成功');
            }else{
                return $this->failed('操作失败');
            }
        }else{
            return $this->failed('请求错误');
        }
    }

    /**
     * 订单批量发货
     */
    public function batchSend(Request $request, Order $OrderModel)
    {
        if($request->isMethod('post')){
            $file = $request->all();
            if(array_key_exists('file',$file)){ //检查数组中此键名是否存在
                unset($file['file']);//删除键名及其值
            }
            if (!$file['url']) {
                return $this->failed('请上传模板');
            }
            if (!$file['express']) {
                return $this->failed('请选择物流公司');
            }
            $arrCSV = array();
            if (($handle = fopen($file['url'], "r")) !== false) {
                $key = 0;
                while (($data = fgetcsv($handle, 0, ",")) !== false) {
                    $c = count($data);
                    for ($x = 0; $x < $c; $x++) {
                        $arrCSV[$key][$x] = trim($data[$x]);
                    }
                    $key++;
                }
                fclose($handle);
            }
            unset($arrCSV[0]);
            
            $list = $this->sendForm($arrCSV,$file['express'],$OrderModel);
            return $this->success(compact('list'));
        }
        $url = $_SERVER['SERVER_NAME'];
        $express_list = Express::get()->toArray();
        $realPath = $OrderModel->getHttps().$url.'/default.csv';
        $fileName = date('YmdHis', time());

        return view('order::admin.order.batch_send', compact('express_list','realPath','fileName'));
    }

    /**
     * 操作批量发货
     */
    public function sendForm($arrCSV,$express,$OrderModel)
    {
        $empty = []; //是否存在
        $error = []; //操作失败
        $cancel = []; //是否取消
        $offline = []; //到店自提
        $send = []; //是否发货
        $success = []; //是否成功
        $pay = []; //是否支付

        $order_list = [];
        
        foreach ($arrCSV as $v) {
            $order = $OrderModel->where([
               ['is_delete','=', 0],
               ['order_no','=', $v[1]],
            ])->first();
            
            if (!$order) {
               //$empty[] = $v[1];
               $empty['order_no'] = $v[1];
               $empty['nickname'] = '';
               $empty['name'] = '';
               $empty['mobile'] = '';
               $empty['address'] = '';
               $empty['express_no'] = $v[2];
               $empty['express'] = $express;
               $empty['order_status_name'] = '订单不存在';
               $order_list[] = $empty;
               continue;
            }
            if ($order->order_status == 4) {
                //$cancel[] = $v[1];
                $order->order_no = $v[1];
                $order->nickname = User::where('id',$order->user_id)->value('nickname');
                $order->order_status_name = '订单已取消';
                $order_list[] = $order;
                continue;
            }
            if ($order->order_status == 2) {
                //$send[] = $v[1];
                $order->order_no = $v[1];
                $order->nickname = User::where('id',$order->user_id)->value('nickname');
                $order->order_status_name = '订单已发货';
                $order_list[] = $order;
                continue;
            }
            if ($order->is_offline) {
                //$offline[] = $v[1];
                $order->order_no = $v[1];
                $order->nickname = User::where('id',$order->user_id)->value('nickname');
                $order->order_status_name = '自提订单';
                $order_list[] = $order;
                continue;
            }
            if ($order->order_status == 0) {
               //$pay[] = $v[1];
                $order->order_no = $v[1];
                $order->nickname = User::where('id',$order->user_id)->value('nickname');
                $order->order_status_name = '订单未支付';
                $order_list[] = $order;
                continue;
            }
            
            $order->express_no = $v[2];
            $order->order_status = 2;
            $order->send_time = date('Y-m-d H:i:s');
            $order->express = $express;

            if (!$order->save()) {
                //$error[] = $v[1];
                $order->order_no = $v[1];
                $order->nickname = User::where('id',$order->user_id)->value('nickname');
                $order->order_status_name = '发货失败';
                $order_list[] = $order;
            } else {
                //$success[] = $v[1];
                $order->order_no = $v[1];
                $order->nickname = User::where('id',$order->user_id)->value('nickname');
                $order->order_status_name = '发货成功';
                $order_list[] = $order;
            }
        };
        return $order_list;
    }

}
